package com.d2.modules.system.permission.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.d2.common.domain.Result;
import com.d2.modules.system.permission.entity.Resource;
import com.d2.modules.system.permission.entity.RoleResource;
import com.d2.modules.system.permission.entity.UserRole;
import com.d2.modules.system.permission.service.IResourceService;
import com.d2.modules.system.permission.service.IRoleResourceService;
import com.d2.modules.system.permission.service.IUserRoleService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("permission/resource")
@Slf4j
public class ResourceController {

    @Autowired
    private IResourceService resourceService;

    @Autowired
    private IRoleResourceService roleResourceService;

    @GetMapping("tree")
    public Result<List<Resource>> tree(Long exclude){
        return Result.success(this.resourceService.tree(exclude));
    }

    @PostMapping("add")
    public Result<Void> add(@RequestBody Resource resource){
        if(resource.getPid() == null){
            resource.setPid(0L);
        }
        resourceService.save(resource);
        return Result.success();
    }

    @Transactional
    @PostMapping("delete")
    public Result<Void> delete(Long id){
        resourceService.removeById(id);
        RoleResource query = new RoleResource();
        query.setResourceId(id);
        roleResourceService.remove(new QueryWrapper<>(query));
        return Result.success();
    }

    @PostMapping("update")
    public Result<Void> update(@RequestBody Resource resource){
        resourceService.updateById(resource);
        return Result.success();
    }
}
